package com.ruanhb.wsp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Created by r on 2018-9-21
 */
@Service
public class WeatherDataCollectionServiceImpl implements WeatherDataCollectionService {


    private static final long TIM_OUT = 1800L;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public void syncDateByCityId(String cityId) {

        String uri = "http://wthrcdn.etouch.cn/weather_mini" + "?citykey=" + cityId;
        saveWeatherData(uri);
    }

    /**
     * 把天气数据放入缓存中
     * @param uri
     */
    private void saveWeatherData(String uri) {
        String key = uri;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }
        //写入缓存
        ops.set(key,strBody,TIM_OUT, TimeUnit.SECONDS);
    }
}
